package asdf.trial;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * about cookie Created by lichengwen on 5/26/16.
 */
public class CookieUtils
{

    private static Logger LGR = LoggerFactory.getLogger(CookieUtils.class);

    public static Cookie getCookie(HttpServletRequest request, String name)
    {
        Cookie cookies[] = request.getCookies();
        if ( cookies != null ) {
            for ( Cookie cookie : cookies ) {
                if ( name.equals(cookie.getName()) ) {
                    return cookie;
                }
            }
        }
        return null;
    }

    public static void setCookie(
            HttpServletResponse response, String name, String value,
            String domain, String path, int maxAge,
            boolean httpOnly, boolean secure)
    {
        if ( response.isCommitted() ) {
            LGR.warn("response committed already, cannot set cookie: {}->{}", name, value);
        } else {
            Cookie ck = new Cookie(name, value);
            ck.setMaxAge(maxAge);
            ck.setPath(path);
            ck.setDomain(domain);
            ck.setHttpOnly(httpOnly);
            ck.setSecure(secure);
            response.addCookie(ck);
        }
    }

    public static void deleteCookie(
            HttpServletRequest request, HttpServletResponse response, String name)
    {
        Cookie ck = getCookie(request, name);
        if ( ck != null ) {
            ck.setMaxAge(0);
            response.addCookie(ck);
        }
    }

}
